package com.softer.chengxin.project.service.impl;

import com.softer.chengxin.common.domin.*;
import com.softer.chengxin.common.enums.*;
import com.softer.chengxin.corp.dao.CorpDao;
import com.softer.chengxin.corp.domin.ApproveDTO;
import com.softer.chengxin.home.dao.MessageDao;
import com.softer.chengxin.home.domin.Message;
import com.softer.chengxin.person.domin.PersonVO;
import com.softer.chengxin.project.dao.ProManagerDao;
import com.softer.chengxin.project.domin.*;
import com.softer.chengxin.project.service.ProManagerService;
import com.softer.chengxin.score.util.ScoreUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangxinrui
 * @date 2018/10/12
 */
@Service
public class ProManagerServiceImpl implements ProManagerService {
    private Logger logger = LoggerFactory.getLogger(ProManagerServiceImpl.class);
    @Autowired
    private ProManagerDao md;
    @Autowired
    private CorpDao cd;
    @Autowired
    private CorpDao corpDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private ScoreUtil scoreUtil;

    /**
     * 加载企业项目查询信息列表
     *
     * @param loginName   登录名
     * @param qyName      企业名
     * @param state       状态
     * @param page        页码
     * @param district    所在区县
     * @param street      所在街道
     * @param cxBeginDate 查询开始日期
     * @param cxEndDate   查询结束日期
     * @return 结果集
     */
    @Override
    public ManagerPageResult load(String loginName, String qyName, String projectName, String state, Page page,
                                  String district, String street, String cxBeginDate, String cxEndDate) {
        if (StringUtils.isBlank(state)) {
            state = "1,2,3,4";
        }
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        int count = md.loadCount(qyName, projectName, state, area, district, street, cxBeginDate, cxEndDate);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ProjectInfoVO> list = md.load(qyName, projectName, state, area, page, district, street, cxBeginDate, cxEndDate);
        jr.setDs(list);
        mpr.setCount(count);
        mpr.setJson(jr);
        return mpr;
    }
    /**
     * 加载企业项目信息审批列表
     *
     * @param loginName   登录名
     * @param qyName      企业名
     * @param state       状态
     * @param page        页码
     * @param district    所在区县
     * @param street      所在街道
     * @param cxBeginDate 查询开始日期
     * @param cxEndDate   查询结束日期
     * @return 结果集
     */
    @Override
    public ManagerPageResult getProSPList(String loginName, String qyName, String projectName, String state, Page page,
                                  String district, String street, String cxBeginDate, String cxEndDate) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String area = null;
        //审核列表查询
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        //TODO
        //查询账号是区管理部门还是市管理部门3市   4区
        String code = md.getDicCodeByLoginName(loginName);
        //区级查询state状态为1
        if( String.valueOf(NumberEnum.FOUR.getNum()).equals(code)){
            //state 1区审核中  4市审核中
            state = String.valueOf(NumberEnum.ONE.getNum());
        }else if( String.valueOf(NumberEnum.THREE.getNum()).equals(code)){
            state = String.valueOf(NumberEnum.FOUR.getNum());
        }else if( "admin".equals(loginName)){
            state = String.valueOf("1,4");
        }
        int count = md.loadCount(qyName, projectName, state, area, district, street, cxBeginDate, cxEndDate);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ProjectInfoVO> list = md.load(qyName, projectName, state, area, page, district, street, cxBeginDate, cxEndDate);
        jr.setDs(list);
        mpr.setCount(count);
        mpr.setJson(jr);
        return mpr;
    }

    /**
     * 加载该管理账号所管理区域的企业项目信息
     *
     * @param loginName 登录的用户名
     * @param qyName    企业名
     * @param state     状态
     * @param page      页码
     * @return 结果
     */
    @Override
    public ManagerPageResult findByCondition(String loginName, String qyName, Integer state, Page page, String proName) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = cd.getDistinct(loginName);
        }
        int count = md.findByConditionCount(qyName, state, area, proName);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr) ;
        }
        List<ProjectInfoVO> list = md.findByCondition(qyName, state, area, page, proName);
        jr.setDs(list);
        mpr.setCount(count);
        mpr.setJson(jr);
        return mpr;
    }

    /**
     * 项目审批
     * @param loginName  登录名
     * @param approveDTO 实体
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult sp(String loginName, ApproveDTO approveDTO) {
        //状态3驳回，其他审核
        if(NumberEnum.THREE.getNum() == approveDTO.getState()){
            //审批
            int num = md.sp(approveDTO.getID(), approveDTO.getState());
            //增加一条审批记录
            corpDao.addProjectOpinion(approveDTO, loginName);
            //查询企业id
            Integer corpId = md.findCorpId(approveDTO.getID());
            //重新算分
            scoreUtil.updateRecord(corpId);
            if (num > Integer.parseInt(Common.ZERO)) {
                //增加通知消息
                addMessage(approveDTO, loginName);
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        //审核，判断市审核还是区审核
        //查询账号是区管理部门还是市管理部门3市   4区
        String code = corpDao.getDicCodeByLoginName(loginName);
        int num = 0;
        if( String.valueOf(NumberEnum.FOUR.getNum()).equals(code)){
            //状态（0保存，1提交审核，2市审核通过，3审核不通过，4区审核通过（市审核中））
            approveDTO.setState(NumberEnum.FOUR.getNum());
            num = md.sp(approveDTO.getID(), approveDTO.getState());
            if (num > Integer.parseInt(Common.ZERO)) {
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
        }else if( String.valueOf(NumberEnum.THREE.getNum()).equals(code) ||  String.valueOf(NumberEnum.ONE_HUNDRED.getNum()).equals(code)){
            //状态（0保存，1提交审核，2市审核通过，3审核不通过，4区审核通过（市审核中））
            approveDTO.setState(NumberEnum.TWO.getNum());
            //审批
            num = md.sp(approveDTO.getID(), approveDTO.getState());
            //增加一条审批记录
            corpDao.addProjectOpinion(approveDTO, loginName);
            //查询企业id
            Integer corpId = md.findCorpId(approveDTO.getID());
            //重新算分
            scoreUtil.updateRecord(corpId);
            if (num > Integer.parseInt(Common.ZERO)) {
                //增加通知消息
                addMessage(approveDTO, loginName);
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 新增通知消息
     *
     * @param approveDTO 审批实体
     * @param loginName  登陆用户
     */
    private void addMessage(ApproveDTO approveDTO, String loginName) {
        ProjectInfoVO pro = md.getCompanyId(approveDTO.getID());
        Message message = new Message();
        message.setAdder(loginName);
        message.setCropid(pro.getCompanyId());
        //企业信息的消息类型定义为0
        message.setType(Integer.parseInt(Common.ZERO));
        message.setUrl(UrlEnum.PROJECT_INFO.getUrl());
        if (approveDTO.getState() == StateEnum.PASS_THROUGH.getCode()) {
            message.setTitle(MessageEnum.PROJECT_INFO_THROUGH.getMsg());
        } else {
            message.setTitle(MessageEnum.PROJECT_INFO_NO_THROUGH.getMsg());
        }
        messageDao.addMessage(message);
    }

    /**
     * 获取该管理账号下的企业下的项目的物业用房信息
     *
     * @param name  人员姓名
     * @param depId 部门id
     * @param page  页码
     * @return 结果
     */
    @Override
    public ManagerPageResult findProjectPerson(String name, String depId, Page page, Integer proId) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        int count = md.findProjectPersonCount(name, depId, proId);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<PersonVO> list = md.findProjectPerson(page, name, depId, proId);
        jr.setDs(list);
        mpr.setCount(count);
        mpr.setJson(jr);
        return mpr;
    }

    /**
     * 获取该管理账号下的企业下的项目的物业用房信息
     *
     * @param address 物业用房详细地址
     * @param nature  物业用房性质
     * @param page    页码
     * @return 结果
     */
    @Override
    public ManagerPageResult findProjectWYYF(String address, Integer nature, Page page, Integer proId) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        int count = md.findProjectWYYFCount(address, nature, proId);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<CompanyHouseVO> list = md.findProjectWYYF(page, address, nature, proId);
        jr.setDs(list);
        mpr.setCount(count);
        mpr.setJson(jr);
        return mpr;
    }

    /**
     * 获取该管理账号下企业下项目下业主委员会信息
     *
     * @param name       人员姓名
     * @param sex        性别
     * @param isDirector 是否主任
     * @param proId      项目id
     * @param page       页码
     * @return 结果
     */
    @Override
    public ManagerPageResult findProjectCommittee(String name, Integer sex, Integer isDirector, Integer proId, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        int count = md.findProjectCommitteeCount(name, sex, proId, isDirector);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ProprietorVO> list = md.findProjectCommittee(page, name, sex, proId, isDirector);
        jr.setDs(list);
        mpr.setCount(count);
        mpr.setJson(jr);
        return mpr;
    }


    /**
     * 选中地图上的位置，并显示相应信息
     *
     * @param id 登陆账号ID
     * @return 信息集合
     */
    @Override
    public List<ProjectInfo> getProInfoHome(Integer id) {
        try {
            String area = md.getArea(id);
            if (StringUtils.isBlank(area)) {
                return new ArrayList<>();
            }
            List<ProjectInfo> list = new ArrayList<>();
            List<Project> proInfoHome = md.getProInfoHome(area);
            if (proInfoHome != null) {
                for (Project p : proInfoHome) {
                    StringBuffer info = new StringBuffer(20);
                    info.append(p.getId()).append("|<p>项目名称：").append(p.getProjectName());
                    info.append("</p><p>所属企业：").append(p.getCompanyName());
                    info.append("</p><p>物业类型：").append(p.getPropertyType());
                    info.append("</p><p>建筑面积：").append(p.getAllArea());
                    info.append("(万平方米)</p><p>诚信等级：").append(p.getDj());
                    info.append("</p>|");
                    info.append(p.getProjectAddress());
                    ProjectInfo projectInfo = new ProjectInfo();
                    projectInfo.setInfo(info.toString());
                    list.add(projectInfo);
                }
            }
            return list;
        } catch (Exception e) {
            logger.error("选中地图上的位置错误", e);
            return new ArrayList<>();
        }
    }

    private ManagerPageResult common(ManagerPageResult mpr,JsonResult jr) {
        jr.setDs(new ArrayList());
        mpr.setJson(jr);
        mpr.setCount(NumberEnum.ZERO.getNum());
        return mpr;
    }

}
